﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web;
using System.Web.UI.WebControls;

namespace Deeper.Common.Web
{
    /// <summary>
    /// 页面打印（预览）及导出到Excel
    /// </summary>
    public static class PrintHelper
    {
        private static void WriteScript(this Page page)
        {
            WriteScript(page, true);
        }

        private static void WriteScript(this Page page, bool isView)
        {
            StringBuilder script = new StringBuilder();
            script.Append(@"<script language=""javascript"">
								function printPreview(content)
								{
									var printWindow = window.open("""","""",""left=2000,top=2000,fullscreen=3"");
									var str = ""<OBJECT id=WebBrowser classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height=0 width=0></OBJECT>"";
									var s = ""<html>\r\n"";
									s += ""<head>"";
									s += ""<link rel='stylesheet' type='text/css' href='/HITCHWeb/INC/style.css'>"";
									s += ""<style media=print>"";
									s += "".NoPrint{display:none;}"";
									s += "".PageNext{page-break-after: always;}"";
									s += ""</style>"";
									s += ""<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>"";
									s += ""</head>"";
									s += ""<body><center>"";
									s += content;
									s += ""</center></body>"";
									s += ""</html>"";
									printWindow.document.write(s);
									printWindow.document.close();
									printWindow.document.body.insertAdjacentHTML(""beforeEnd"", str);");

            if (isView)	//打印预览
            {
                script.AppendLine("printWindow.document.all.WebBrowser.ExecWB(7,1);");
                script.AppendLine("printWindow.close();");
            }
            else	//直接打印
            {
                script.AppendLine("printWindow.document.all.WebBrowser.ExecWB(6,6);");
                script.AppendLine("printWindow.close();");
            }

            script.AppendLine("}</script>");


            if (!page.ClientScript.IsStartupScriptRegistered("print"))
            {
                page.ClientScript.RegisterStartupScript(typeof(Page), "print", script.ToString());
            }

        }


        /// <summary>
        /// 直接打印
        /// </summary>
        /// <param name="ctrl">web控件</param>
        public static void Print(this WebControl ctrl)
        {
            WriteScript(ctrl.Page, false);

            StringBuilder actscript = new StringBuilder();
            actscript.Append("          <script language='javascript'>");
            actscript.AppendFormat("        var control = document.getElementById('{0}');", ctrl.ClientID);
            actscript.Append("              if(typeof(control) != 'undefined'){");
            actscript.Append("                  var content = control.innerHTML;");
            actscript.Append("                  content = content.replace(\"'\",\"\\'\");");
            actscript.Append("                  printPreview(content);");
            actscript.Append("          }</script>");

            ctrl.Page.ClientScript.RegisterStartupScript(typeof(Page), " ", actscript.ToString());
        }

        /// <summary>
        /// 直接打印
        /// </summary>
        /// <param name="ctrl">web控件</param>
        /// <param name="title">打印标题</param>
        public static void Print(this WebControl ctrl, string title)
        {
            WriteScript(ctrl.Page, false);
            StringBuilder actscript = new StringBuilder();
            actscript.Append("              <script language='javascript'>");
            actscript.AppendFormat("            var control = document.getElementById('{0}');", ctrl.ClientID);
            actscript.Append("                  if(typeof(control) != 'undefined'){");
            actscript.Append("                      var content = control.innerHTML;");
            actscript.Append("                      content = content.replace(\"'\",\"\\'\");");
            actscript.Append("                      content = content.replace(\"<!--page-->\",\"<p class=\\'PageNext\\'></p>\");");
            actscript.AppendFormat("                content = content.replace(\"<!--title-->\",\"{0}\");", title);
            actscript.Append("                      printPreview(content);");
            actscript.Append("              }</script>");

            ctrl.Page.ClientScript.RegisterStartupScript(typeof(Page), " ", actscript.ToString());
        }


        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="ctrl">web控件</param>
        public static void PrintView(this WebControl ctrl)
        {
            WriteScript(ctrl.Page);
            StringBuilder actscript = new StringBuilder();
            actscript.Append("          <script language='javascript'>");
            actscript.AppendFormat("        var control = document.getElementById('{0}');", ctrl.ClientID);
            actscript.Append("              if(typeof(control) != 'undefined'){");
            actscript.Append("                  var content = control.innerHTML;");
            actscript.Append("                  content = content.replace(\"'\",\"\\'\");");
            actscript.Append("                  printPreview(content);");
            actscript.Append("          }</script>");

            ctrl.Page.ClientScript.RegisterStartupScript(typeof(Page), " ", actscript.ToString());
        }

        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="ctrl">web控件</param>
        /// <param name="title">打印标题</param>
        public static void PrintView(this WebControl ctrl, string title)
        {
            WriteScript(ctrl.Page);
            StringBuilder actscript = new StringBuilder();
            actscript.Append("              <script language='javascript'>");
            actscript.AppendFormat("            var control = document.getElementById('{0}');", ctrl.ClientID);
            actscript.Append("                  if(typeof(control) != 'undefined'){");
            actscript.Append("                      var content = control.innerHTML;");
            actscript.Append("                      content = content.replace(\"'\",\"\\'\");");
            actscript.Append("                      content = content.replace(\"<!--page-->\",\"<p class=\\'PageNext\\'></p>\");");
            actscript.AppendFormat("                content = content.replace(\"<!--title-->\",\"{0}\");", title);
            actscript.Append("                      printPreview(content);");
            actscript.Append("              }</script>");

            ctrl.Page.ClientScript.RegisterStartupScript(typeof(Page), " ", actscript.ToString());
        }

        /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <param name="ctl">web控件</param>
        /// <param name="filename">导出的excel文件名称</param>
        public static void ExportExcel(this WebControl ctl, string filename)
        {
            ctl.Visible = true;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "UTF8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(filename, Encoding.UTF8) + ".xls\"");
            HttpContext.Current.Response.ContentType = "Application/ms-excel";

            ctl.Page.EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            ctl.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
        }

    }
}
